import Previewer from "./previewer.js";
import * as Paged from "../index.js";

window.Paged = Paged;

// 确保document 已经加载完毕
let ready = new Promise(function (resolve, reject) {
	if (
		//Document.readyState 属性描述了document 的加载状态
		document.readyState === "interactive" ||
		document.readyState === "complete"
	) {
		resolve(document.readyState);
		return;
	}

	document.onreadystatechange = function ($) {
		if (document.readyState === "interactive") {
			resolve(document.readyState);
		}
	};
});

let config = window.PagedConfig || {
	//是否自动执行预览
	auto: true,
	//预览器执行预览前的回调
	before: undefined,
	//预览器执行预览后的回调
	after: undefined,
	content: undefined,
	stylesheets: undefined,
	renderTo: undefined,
	settings: undefined,
};

let previewer = new Previewer(config.settings);

// document加载完毕后预览器执行预览
ready.then(async function () {
	let done;
	if (config.before) {
		//预览器执行预览前的回调
		await config.before();
	}

	if (config.auto !== false) {
		//自动执行预览
		done = await previewer.preview(
			config.content,
			config.stylesheets,
			config.renderTo
		);
	}

	if (config.after) {
		//预览器执行预览后的回调
		await config.after(done);
	}
});

export default previewer;
